import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import { AVILIABLE_TASK_MAP } from '../../../../common/constants';
import Pie from './Pie';
import Bar from './Bar';
import s from './AbnormalCounts.module.css';

export default function AbnormalCounts({ className, taskType, jobs }) {
	const { abnormalCounts, total } = jobs.reduce(
		(obj, job) => {
			if (AVILIABLE_TASK_MAP[taskType]) {
				obj.total += job[`${taskType}Settings`]?.length || 0;
				job[`${taskType}Result`].forEach(x => {
					obj.abnormalCounts += x.result.warnings.length;
				});
			} else {
				obj.total += 1;
				obj.abnormalCounts +=
					job[`${taskType}Result`]?.securityStatus === 'warning'
						? 1
						: 0;
			}

			return obj;
		},
		{ total: 0, abnormalCounts: 0 }
	);
	return (
		<div className={cn(className, s.abnormalCounts)}>
			<Pie abnormalCounts={abnormalCounts} total={total} />
			<Bar abnormalCounts={abnormalCounts} total={total} />
		</div>
	);
}

AbnormalCounts.propTypes = {
	className: PropTypes.string,
	taskType: PropTypes.string.isRequired,
	jobs: PropTypes.arrayOf(
		PropTypes.shape({
			httpResult: PropTypes.object,
			httpSettings: PropTypes.object.isRequired,
			pingResult: PropTypes.object,
			pingSettings: PropTypes.object.isRequired,
		})
	),
};

AbnormalCounts.defaultProps = {
	className: s.abnormalCounts,
};
